/* eslint-disable react-hooks/exhaustive-deps */
import {
  Button,
  message,
  Input,
  Row,
  Col,
  Card,
  Form,
  Modal,
  notification,
  Spin,
  Space,
} from 'antd';
import React, { useState,  useEffect, useContext } from 'react';
import { ProFormSelect } from '@ant-design/pro-form';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import Scheduler from './components/Scheduler';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import {
  queryPageList,
  queryPageListPlain,
  updateTask,
  queryDeptList,
  queryTagList,
} from './service';
import { removeTest } from '@/pages/platform/book/service';
import EntryDetail from './components/EntryDetail';
import { UserContext } from '@/layouts/UserProvider';
import moment from 'moment';
const TableList = (props) => {
  const [queryForm] = Form.useForm();
  const [deptList, setDeptList] = useState({});
  const [tagList, setTagList] = useState({});
  const userCtx = useContext(UserContext);
  const [formQueryList, setFormQueryList] = useState({
    limit: 100000, //
    group: '', // 部门名称
    task_tag_name: '', // 预约任务标签名称
    available_status: 3, // 是否可用。1 可用 2 不可用 3 全部。 不传的时候默认为3 全部
    creator_name: '', // 预约人姓名。支持模糊查询
    appointment_name: '',
    offset: 0, //
    start_day: moment().format('YYYY-MM-DD'),
    end_day: moment().format('YYYY-MM-DD'),
    status: null,
  });
  const [conflictCount, setConflictCount] = useState(0);
  const [eventListData, setEventListData] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [type, setType] = useState(0);
  const [addFormData, setAddFormData] = useState(null);
  const [modalUpdateVisible, setModalUpdateVisible] = useState(false);
  const [updateFormData, setUpdateFormData] = useState({})
  const [modalVisibleDetail, setModalVisibleDetail] = useState(false);
  const [entryDetail, setEntryDetail] = useState(null);
  const [loadingListData, setLoadingListData] = useState(false);
  const [listType, setListType] = useState('day');
  const userType = userCtx.userInfo?.type// 1管理员 2基础 3普通 4超级权限
  const permits = userCtx.userPermits;
  const [selectStatus, setSelectStatus] = useState(false)
  console.log("&&&&&&userType&&&&&&&&")
  console.log('userType==============',userType)

  useEffect(() => {
    queryDeptList({ limit: 100000, offset: 0 })
      .then(({ code, data = [], msg }) => {
        if (code === '200') {
          const normalData = data.reduce((next, { group }) => ({ ...next, [group]: group }), {});
          setDeptList(normalData);
        } else {
          setDeptList({});
        }
      })
      .catch(() => { });
    queryTagList({ limit: 100000, offset: 0, is_active: 1 })
      .then(({ code, data = [], msg }) => {
        if (code === '200') {
          const normalData = (data ?? []).reduce(
            (next, { name }) => ({ ...next, [name]: name }),
            {},
          );
          setTagList(normalData);
        } else {
          setTagList({});
        }
      })
      .catch(() => { });
    handleQueryPageList();
  }, []);
  const handleQueryPageList = async (payloads, type = listType) => {
    setEventListData([])
    setLoadingListData(true);
    const paramsPlain = payloads || formQueryList;
    const queryHandler = type === 'list' ? queryPageListPlain : queryPageList;
    const { start_day, end_day, ...params } = paramsPlain
    await queryHandler({
      ...params,
      ...(type !== 'list' && {
        start_day,
        end_day
      }),
      available_status: params.available_status === null ? null : +params.available_status,
      status: params.status === null ? null : +params.status,
    })
      .then(({ code, data, msg }) => {
        if (code === '200') {
          if (data) {
            const { conflicts = 0, details = [] } = data;
            setConflictCount(conflicts ?? 0);
            setEventListData(details ?? []);
          }
        }
      })
      .catch(() => { })
      .finally(() => {
        setLoadingListData(false);
      });
  };
  const resetFormList = () => {
    queryForm.resetFields();
    setFormQueryList({
      limit: 100000, //
      group: '', // 部门名称
      task_tag_name: '', // 预约任务标签名称
      available_status: 3, // 是否可用。1 可用 2 不可用 3 全部。 不传的时候默认为3 全部
      appointment_name: '', // 预约人姓名。支持模糊查询
      offset: 0, //
      start_day: formQueryList.start_day,
      end_day: formQueryList.end_day,
      status: null,
    });
    handleQueryPageList({
      limit: 100000, //
      group: '', // 部门名称
      task_tag_name: '', // 预约任务标签名称
      available_status: 3, // 是否可用。1 可用 2 不可用 3 全部。 不传的时候默认为3 全部
      appointment_name: '', // 预约人姓名。支持模糊查询
      creator_name: '',
      offset: 0, //
      start_day: formQueryList.start_day,
      end_day: formQueryList.end_day,
      status: null,
    });
  };
  //删除
  const handleDelTest = async({ id }) => {
  
  Modal.confirm({
    icon: <ExclamationCircleOutlined />,
    content: '是否要删除？',
    okText: '确认',
    cancelText: '取消',
    
    onOk: async() => {
      await removeTest({  id })
   .then(({ code, msg }) => {
      if (String(code) === '200') {
        message.success('操作成功！');
        handleQueryPageList();
      } else {
        message.success(msg || '操作失败！');
      }
    })
    .catch(() => {
      notification.warning({ message: '异常', description: '网络异常！' });
    });
    },
  });
};
  const onSelect = async (data, type) => {
    if (type === 'update') {
      setModalUpdateVisible(true);
      setUpdateFormData(data);
      return;
    }
    if (data.resource.available_status != 1) {
      message.warning('该车辆不可用请重新选择！');
      return
    }

    // console.log('wmh :',userCtx);
    const finalStartTime = moment(data?.from)
    const finalEndTime = moment(data?.to).add(type === 'DAY' ? 0.5 : 24, 'hours');
    if ((finalEndTime- finalStartTime) === 1800000 ) {
      return;
    }
    const initialValues = {
      car_id: '',
      dateTime: finalStartTime ? [finalStartTime, finalEndTime] : null,
      // appointment_id: '',
      driver_id:null,
      tester_id:null,
      task_tag_id: null,
      content: '',
      ...data,
      ...data.resource,
    }
    setAddFormData(initialValues);
    setModalVisible(true)
    setType(1)
  };
  const onScreenshotChange = (data) => {
    setLoadingListData(true);
    const payloads = {
      ...formQueryList,
      start_day: data.from ? moment(data.from).format('YYYY-MM-DD') : '',
      end_day: data.to ? moment(data.to).format('YYYY-MM-DD') : '',
    };
    setFormQueryList(payloads);
    setListType(data.type)
    handleQueryPageList(payloads, data.type);
  };
  const handleAddDataConfirm = () => {
    setModalVisible(false);
    setAddFormData(null)
    handleQueryPageList();
  };
  const handleUpdateDataConfirm = () => {
    setModalUpdateVisible(false)
    handleQueryPageList();
  };
  const onEventClick = (data) => {
    console.log('%%%%%%%%%%%%%%')
    console.log(data)
    const { status } = data;
    handleEntryDetail(data);
    // if (+status === 1) {
    //   if (!(['1', '4'].includes(String(userType)))) {
    //     //管理员： 点击黄色待确认预约可以选择确认或者取消
    //     return;
    //   }
    //   onCheck(data);
    // } else {
    //   handleEntryDetail(data);
    // }
  };
  const onCheck = async ({ status, id }) => {
    await updateTask({ status, id })
      .then(({ code, msg }) => {
        if (String(code) === '200') {
          message.success('操作成功！');
          handleQueryPageList();
        } else {
          message.success(msg || '操作失败！');
        }
      })
      .catch(() => {
        notification.warning({ message: '异常', description: '网络异常！' });
      });
  };
  const handleEntryDetail = (data) => {
    if (!(['1', '4'].includes(String(userType))) && !permits.includes('detailTask')) {
      return;
    }
    if (data.status == 1) {
      setSelectStatus(false)
    } else {
      setSelectStatus(true)
    }
    setModalVisibleDetail(true);
    setEntryDetail(data);
  };
  return (
    <>
      <div
        style={{ marginBottom: '16px', padding: '24px', paddingBottom: '0', background: '#fff' }}
      >
        <Form
          form={queryForm}
          layout="horizontal"
          labelCol={{ md: 8, sm: 24, xs: 24 }}
          wrapperCol={{ md: 16, sm: 24, xs: 24 }}
          onValuesChange={(changeValues) => {setFormQueryList({ ...formQueryList, ...changeValues })}}
        >
          <Row gutter={24}>
            <Col md={8} sm={24} xs={24}>
              <ProFormSelect name="group" label="车辆所属部门" showSearch valueEnum={deptList} />
            </Col>
            <Col md={8} sm={24} xs={24}>
              <ProFormSelect name="task_tag_name" label="任务标签" showSearch valueEnum={tagList} />
            </Col>
            <Col md={8} sm={24} xs={24}>
              <ProFormSelect
                name="available_status"
                label="车辆是否可用"
                showSearch
                valueEnum={{ 1: '可用', 2: '不可用' }}
              />
            </Col>
            <Col md={8} sm={24} xs={24}>
              <ProFormSelect
                name="status"
                label="任务状态"
                showSearch
                valueEnum={{ 1: '待审核', 2: '已确认', 3: '已取消' }}
              />
            </Col>
            <Col md={8} sm={24} xs={24}>
              <Form.Item name="appointment_name" label="预约人">
                <Input maxLength={256}/>
              </Form.Item>
            </Col>
            <Col md={8} sm={24} xs={24}>
              <Form.Item label="&nbsp;" colon={false}>
                <Row justify="end">
                  <Space>
                    <Button onClick={() => handleQueryPageList()}>搜索</Button>
                    <Button onClick={() => resetFormList()}>重置</Button>
                  </Space>
                </Row>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
      <Card style={{ marginTop: 8 }} gutter={8} title={`最近两周冲突任务数量 : ${conflictCount}`}
     extra={<Button
      type="primary"
      key="primary"
      onClick={()=>{
      // const finalStartTime = moment(data?.from)
      // const finalEndTime = moment(data?.to).add(type === 'DAY' ? 0.5 : 24, 'hours');
      const initialValues = {
        car_id: null,
        dateTime:  null,
        // appointment_id: '',
        driver_id:null,
        tester_id:null,
        task_tag_id: null,
        content: '',
      }
       setModalVisible(true);
       setAddFormData(initialValues);
       setType(0);
      }}>添加预约任务</Button>}
      >
        <Spin spinning={loadingListData}>
          <Scheduler
            handleDelTest={handleDelTest}
            onSelect={onSelect}
            onScreenshotChange={onScreenshotChange}
            onEventClick={onEventClick}
            onCheck={onCheck}
            data={eventListData}
          />
        </Spin>
        {modalVisible && addFormData && (
            <CreateForm
              modalVisible={modalVisible}
              data={addFormData}
              type={type}
              onCancel={() => {setModalVisible(false);setAddFormData(null)}}
              onConfirm={handleAddDataConfirm}
            />
        )}
        {modalUpdateVisible && <UpdateForm
          modalVisible={modalUpdateVisible}
          data={updateFormData}
          onCancel={() => setModalUpdateVisible(false)}
          onConfirm={handleUpdateDataConfirm}
        />}
        {modalVisibleDetail && (
          <EntryDetail
            modalVisible={modalVisibleDetail}
            onSelect={onSelect}
            onCheck={onCheck}
            data={entryDetail}
            selectStatus= {selectStatus}
            onCancel={() => setModalVisibleDetail(false)}
          />
        )}
      </Card>
    </>
  );
};

export default TableList;
